package fhp.hlhj.giantfold.activity.user
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.support.v4.content.FileProvider
import android.util.Log
import android.view.Gravity
import com.ali.auth.third.core.model.User
import com.bumptech.glide.Glide
import com.lzy.okgo.OkGo
import com.lzy.okgo.convert.StringConvert
import com.lzy.okgo.model.HttpParams
import com.lzy.okrx.adapter.ObservableBody
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import fhp.hlhj.giantfold.BaseActivity
import fhp.hlhj.giantfold.Contents
import fhp.hlhj.giantfold.R
import fhp.hlhj.giantfold.interfaces.TakePhotoInterface
import fhp.hlhj.giantfold.customView.IconPopup
import fhp.hlhj.giantfold.event.RefreshInfoEvnet
import fhp.hlhj.giantfold.interfaces.IChangeInfo
import fhp.hlhj.giantfold.interfaces.IUser
import fhp.hlhj.giantfold.javaBean.ChangeInfoBean
import fhp.hlhj.giantfold.javaBean.UserInfoBean
import fhp.hlhj.giantfold.network.Urls
import fhp.hlhj.giantfold.presenter.ChangeInfoPresenter
import fhp.hlhj.giantfold.presenter.UserPresenter
import fhp.hlhj.giantfold.utils.LogUtil
import kotlinx.android.synthetic.main.activity_user_info_aty.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

class UserInfoAty : BaseActivity(), TakePhotoInterface,IUser,IChangeInfo {
    private val TYPE_TAKE_PHOTO = 1//Uri获取类型判断
    private val CODE_TAKE_PHOTO = 1//相机RequestCode
    private val CODE_PICK_PHOTO = 2//相机RequestCode
    private var mCurrentPhotoPath: String? = null
    private  var  fileUri: Uri?=null
    private lateinit var presenter:UserPresenter
    private lateinit var changePresenter: ChangeInfoPresenter

    override fun initView() {
        changePresenter=ChangeInfoPresenter(this)
        presenter= UserPresenter(this)
        val params = HttpParams()
        params.put("user_id",Contents.userId)
        presenter.getUser(params)
    }

    /**
     * 相机照相
     */
    override fun takePhoto() {
        if (Build.VERSION.SDK_INT >= 24) {
            val takeIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            val photoUri = get24MediaFileUri(TYPE_TAKE_PHOTO)
            fileUri=photoUri
            takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
            startActivityForResult(takeIntent, CODE_TAKE_PHOTO)
        } else {
            LogUtil.log("点击了")
            val takeIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            val photoUri = getMediaFileUri(TYPE_TAKE_PHOTO)
            fileUri=photoUri
            takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
            startActivityForResult(takeIntent, CODE_TAKE_PHOTO)
        }
    }
    /**
     * 从相册选择
     */
    override fun pickPhoto() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .showSingleMediaType(true)
                .countable(true)
                .maxSelectable(1)
                .spanCount(3)
                //                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .theme(R.style.Matisse_Zhihu)
                .imageEngine(GlideEngine())
                .forResult(CODE_PICK_PHOTO)
    }

    override fun getContentId(): Int {
        return R.layout.activity_user_info_aty
    }

    override fun initListener() {
        btExit.setOnClickListener {
            finish()
        }
        btIcon.setOnClickListener {
            IconPopup(this,this).showAtLocation(father,Gravity.BOTTOM,0,0)
        }
        btName.setOnClickListener {
            startActivity(Intent(this,UserNickAty::class.java))
        }
    }

    /**
     * 获取url sdk>24
     */
    fun get24MediaFileUri(type: Int): Uri? {
        val mediaStorageDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "GiantImgs")
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null
            }
        }
        //创建Media File
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        val mediaFile: File
        if (type == TYPE_TAKE_PHOTO) {
            mediaFile = File(mediaStorageDir.path + File.separator + "IMG_" + timeStamp + ".jpg")
        } else {
            return null
        }
        return FileProvider.getUriForFile(this, packageName + ".fileprovider", mediaFile)
    }

    /**
     * 获取uri，sdk<24
     */
    fun getMediaFileUri(type: Int): Uri? {
        val mediaStorageDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "GiantImgs")
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null
            }
        }
        //创建Media File
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        val mediaFile: File
        if (type == TYPE_TAKE_PHOTO) {
            mediaFile = File(mediaStorageDir.path + File.separator + "IMG_" + timeStamp + ".jpg")
        } else {
            return null
        }
        return Uri.fromFile(mediaFile)
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode!= Activity.RESULT_OK)return
        when(requestCode){
            CODE_TAKE_PHOTO->{
                if (data!=null){
                    Log.e("info", "data is not null");
                    val uri=data.getParcelableArrayExtra("data") as Bitmap
                    Glide.with(this).load(uri).asBitmap().into(userIcon)
                }else{
                    Log.e("info", "data is  null");
                     if (Build.VERSION.SDK_INT >= 24){
                            var bitmap: Bitmap? =null
                            try {
                                bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri));
                            } catch ( e:FileNotFoundException) {
                                e.printStackTrace()
                            }
                            userIcon.setImageBitmap(bitmap)
                     }else {
                         Log.e("info", "path is "+fileUri!!.path);
                         Glide.with(this).load(fileUri?.path).asBitmap().into(userIcon)
                     }
                }
            }
            CODE_PICK_PHOTO->{
                if (data!=null){
                    val pathResult = Matisse.obtainPathResult(data)
                    val file = File(pathResult[0])
                    Glide.with(this).load(pathResult[0]).asBitmap().into(userIcon)
                    val params = HttpParams()
                    LogUtil.log("上传文件路径${file.absolutePath}")
                    params.put("column_name","head_pic")
                    params.put("new_value",file)
                    params.put("user_id",Contents.userId)
                    changePresenter.changeInfo(params)
                }
            }
        }
    }
    @Throws(IOException::class)
    private fun createImageFile(b: Bitmap): File {
        // Create an image file name
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(Date())
        val imageFileName = "JPEG_" + timeStamp + "_"
        //.getExternalFilesDir()方法可以获取到 SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
        val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        //创建临时文件,文件前缀不能少于三个字符,后缀如果为空默认未".tmp"
        val image = File.createTempFile(
                imageFileName, /* 前缀 */
                ".jpg", /* 后缀 */
                storageDir      /* 文件夹 */
        )
        mCurrentPhotoPath = image.absolutePath
        var fOut: FileOutputStream? = null
        try {
            fOut = FileOutputStream(image)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }

        b.compress(Bitmap.CompressFormat.PNG, 100, fOut)
        try {
            fOut!!.flush()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        try {
            fOut!!.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return image
    }

    /**
     * 回调
     */
    override fun showLoading() {
        loadingDialog.show()
    }

    override fun getUser(userInfoBean: UserInfoBean) {
        loadingDialog.dismiss()
        if (userInfoBean.code==200){
            Glide.with(this).load(Urls.BaseUrl+"/"+userInfoBean.data.head_pic).dontAnimate().placeholder(R.mipmap.exp2).into(userIcon)
            userId.text=userInfoBean.data.id
            userName.text=userInfoBean.data.nick_name
            tvPhone.text=userInfoBean.data.phone
        }
    }
    override fun changeInfo(changeInfoBean: ChangeInfoBean) {
        loadingDialog.dismiss()
        if (changeInfoBean.code==200){
            val params = HttpParams()
            params.put("user_id",Contents.userId)
            presenter.getUser(params)
        }
    }
    @Subscribe(threadMode = ThreadMode.POSTING)
    fun refreshInfo(refreshInfoEvnet: RefreshInfoEvnet){
        val params = HttpParams()
        params.put("user_id",Contents.userId)
        presenter.getUser(params)
    }

}
